import os,json
from util.sketlonize import Sketlonize
from util.corner_detecot import CornerDetector
from util.vessel_seg import BloodVesselEmbedding,VesselVector
from util.graph import Graph



if __name__ == '__main__':

    # 获取配置
    data_path='../Dataset/infantImages'
    # 读取数据字典
    with open(os.path.join(data_path, 'annotations.json'), 'r') as f:
        data_dict = json.load(f)
    visual_dir='./experiments/new_feature'
    if not os.path.exists(visual_dir):
        os.makedirs(visual_dir)
    data_set_path='./experiments/dataset'
    vascular_dir=os.path.join(data_set_path,'vascular')
    image_dir= os.path.join(data_set_path,'images')
    image_name= '1243.jpg'
    vascular_path=os.path.join(vascular_dir,image_name)
    skeletoner=Sketlonize(0.35)
    x,y=data_dict[image_name]['optic_disc_pred']['position']
    x=int(x*3/8)
    y=int(y*3/8)
    
    skeleton,vascular_cnt_img,vascular_cnt=skeletoner.sketlonize(vascular_path,optic_disc_coor=(x,y), min_size=100)
    # 拐点检测
    corner_detector = CornerDetector()
    points = corner_detector.point_detector(skeleton)
    # corner_detector.visual_point(skeleton, points, save_path=os.path.join(visual_dir,'harris.jpg'))

    # 分叉点检测
    bifurcation_points = corner_detector.detect_bifurcation_points(skeleton,points)
    
    # 创建 BloodVesselEmbeddingWithVisualization 实例
    vessel_embedding = BloodVesselEmbedding()
    
    # 构建血管结构和嵌入
    vessels = vessel_embedding.build_vessel_embedding(skeleton, vascular_cnt, vascular_cnt_img, points, bifurcation_points, (x, y))
    
    # 可视化结果
    vessel_embedding.visualize_vessels(skeleton, vessels, points, bifurcation_points, save_path=os.path.join(visual_dir, 'vessels.jpg'))
    
    # 重要点检测
    vessel_vector=VesselVector()
    simplied_vessels=[]
    important_points=[]
    for vessel in vessels:
        simply_vessel=vessel_vector.Simplify(vessel)
        simplied_vessels.append(simply_vessel)
        important_points.extend(vessel_vector.important_point_detecot(simply_vessel))
    
    # 可视化重要点
    vessel_vector.visual_portant_points(skeleton,important_points,5,os.path.join(visual_dir,'important_points.jpg'))
    
    # 可视化简化后的血管
    vessel_embedding.visualize_vessels(skeleton, simplied_vessels, points, bifurcation_points, save_path=os.path.join(visual_dir, 'simplied_vessels.jpg'))
    
    # 纠正血管方向
    vessels = vessel_vector.dir_rection_check(simplied_vessels, (x, y))
    # 可视化血管方向
    vessel_embedding.visual_vessel_direction(skeleton, vessels, save_path=os.path.join(visual_dir, 'vessel_direction.jpg'))
    
    # 创建图
    g=Graph(skeleton.shape[0],skeleton.shape[1])
    g.build_from_vessel(vessels)
    g.visualization(save_path=os.path.join(visual_dir, 'graph.jpg'))
    